package service;

import dao.UserDao;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @Description 作为用户的UserService层
 * @Author hhy
 */
public class UserService {

    private String name = "";
    UserDao userDao = new UserDao();
    Scanner sc =  new Scanner(System.in);


    /**
     *
     * @return 返回是否登录成功
     */
    public boolean userLogin(){
        if (cooike()){
            return true;
        }
        System.out.println("请输入你的用户名");
        String username = sc.next();
        this.name =username;
        System.out.println("请输入你的密码");
        String password = sc.next();
        saveCooike(username);
        return userDao.userLogin(username,password);
    }

    /**
     *
     * @return 返回是否注册成功
     */
    public boolean userRegister(){
        System.out.println("请输入你的用户名");
        String username = sc.next();
        System.out.println("请输入你的密码");
        String password = sc.next();
        return userDao.userRegister(username,password);
    }

    /**
     * 测试功能，用于查看用户是否被注册
     */
    public void selectAlluser(){
        userDao.selectAlluser();
    }

    public String getUserName(){
        return name;
    }

    public void saveCooike(String name){
        HashMap<String, String> map = new HashMap<>();
        map.put(name,"true");
        map.put("time",System.currentTimeMillis()+"");
        File file = new File("cooike.txt");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
            outputStream.writeObject(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public boolean cooike() {
        File file = new File("cooike.txt");
        if (!file.exists()) {
            return false;
        }
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(file));
            Map<String, String> map = (Map<String, String>) inputStream.readObject();
            //设置cooike的时间为10秒，超过了10秒就重新登录
            if (Long.valueOf(map.get("time")) + 10000 > System.currentTimeMillis()) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}



